import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
export interface ProductSearchState {
  loading: boolean
  error: string | null
  data: any
  pagination: any
}
const initialState: ProductSearchState = {
  loading: true,
  error: null,
  data: [],
  pagination: null
}
export const getProductSearch = createAsyncThunk('productDetail/getProductSearch', async (paramaters: {
  keywords: string,
  nextPage: number | string,
  pageSize: number | string
}) => {
  let url = `http://123.56.149.216:8080/api/touristRoutes?pageNumber=${paramaters.nextPage}&pageSize=${paramaters.pageSize}`
  if (paramaters.keywords) {
    url += `&keywords=${paramaters.keywords}`
  }
  const res = await axios.get(url)
  return {
    data: res.data,
    pagination: JSON.parse(res.headers['x-pagination'])
  }
})
export const productSearchSlice = createSlice({
  name: 'productDetail',
  initialState,
  reducers: {

  },
  extraReducers: {
    [getProductSearch.pending.type]: (state) => {
      state.loading = true
    },
    [getProductSearch.fulfilled.type]: (state, action: PayloadAction<any>) => {
      state.data = action.payload.data
      state.pagination = action.payload.pagination
      state.loading = false
      state.error = null
    },
    [getProductSearch.rejected.type]: (state, action: PayloadAction<string | null>) => {
      state.loading = false
      state.error = action.payload
    }
  }
})